<template>
  <div class="app-container">
    <div class="left-container">
      <div class="up-list">
        <div class="leftList-container">
          <div class="unConfig-container" id="orderBack-step1">
            <div class="unConfig-title">
              <div
                :class="[isLookUnConfigBtn ? 'expand' : 'unExpand']"
                @click="isLookUnConfigBtn = !isLookUnConfigBtn">
                <span>▲</span>
              </div>
              <div>
                <span>未布置的点</span>
              </div>
            </div>
            <div v-show="isLookUnConfigBtn" class="unConfig-list">
              <div
                v-for="(item, index) in unConfigBtnList"
                :key="index"
                :id="item.id"
                class="list-item"
                :class="[
                  currentSelectLeftBtnItem &&
                  currentSelectLeftBtnItem.id == item.id
                    ? 'active-item'
                    : '',
                ]"
                :style="[
                  {'cursor': mousePoint}
                ]"
                :draggable="true"
                @dragstart="dragStart($event, item)"
                @dragend="dragEnd($event, item)">
                <div class="item-content">
                  <div class="svg-img-icon">
                    <img :src="item.status == 1 ? alarmSrc : pointSrc" alt="" />
                  </div>
                  <div class="content">
                    <span>{{ item.zoneName }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="config-container" id="orderBack-step2">
            <div class="config-title">
              <div
                :class="[isLookConfigBtn ? 'expand' : 'unExpand']"
                @click="isLookConfigBtn = !isLookConfigBtn">
                <span>▲</span>
              </div>
              <div>
                <span>已布置的点</span>
              </div>
            </div>
            <div v-show="isLookConfigBtn" class="config-list">
              <div
                v-for="(item, index) in configBtnList"
                :key="index"
                class="list-item"
                :class="[
                  currentSelectLeftBtnItem &&
                  currentSelectLeftBtnItem.id == item.id
                    ? 'active-item'
                    : '',
                ]"
                @click="clickBtnItem(item)">
                <div class="item-content">
                  <div class="svg-img-icon">
                    <img :src="item.status == 1 ? alarmSrc : pointSrc" alt="" />
                  </div>
                  <div class="content">
                    <span>{{ item.zoneName }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="down-btn" id="orderBack-step6">
        <el-button type="primary" @click="savePos" size="mini">保存</el-button>
        <el-button type="primary" @click="clearAllPos" size="mini">清空</el-button>
        <el-button type="primary" @click="refresh" size="mini">还原</el-button>
      </div>
    </div>

    <div id="lookMap" @dragover.prevent @drop.prevent="receiveOnBtn">
      <div class="operaBtn-container">
        <div id="orderBack-step4">
          <i class="el-icon-rank"></i>
        </div>
        <div id="orderBack-step5">
          <i class="iconfont icon-xiangpica"></i>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { leaflet as L } from "@/assets/plugin/leaflet-measure-path.js";
  import "leaflet/dist/leaflet.css";
  import "@geoman-io/leaflet-geoman-free";
  import "@geoman-io/leaflet-geoman-free/dist/leaflet-geoman.css";
  import pointSrc from "@/assets/images/point.png";
  import alarmSrc from "@/assets/images/alarm.png";
  import steps from "./orderBackSteps"

  export default {
    name: "OrderBack",
    data() {
      return {
        map: null, // 地图索引
        zoom: -1, // 地图当前缩放级别
        layerDatas: [], // 地图标记点集合
        defaultIcon: "map/point.png", // 默认marker点图标
        alarmIcon: "map/alarm.png", //报警icon点图标
        isLookUnConfigBtn: true,
        isLookConfigBtn: true,
        unConfigBtnList: [],
        configBtnList: [],
        currentSelectLeftBtnItem: null, //左侧选中
        pointSrc: pointSrc,
        alarmSrc: alarmSrc,
        popup: null,
        mousePoint: "grab"
      };
    },
    mounted() {
      this.initMap();//初始化地图
      this.getList();//获取列表
      setTimeout(() => {
        this.guide()
      }, 500)
    },
    beforeDestroy() {
      this.removeMapListener();
    },
    methods: {
      guide() {//页面引导功能
        this.$driver.defineSteps(steps)
        this.$driver.start()
      },
      getList() {
        let findUnConfigLocalData = localStorage.getItem("unConfigBtnList");
        if (findUnConfigLocalData) {
          findUnConfigLocalData = JSON.parse(findUnConfigLocalData);
        }
        let findConfigLocalData = localStorage.getItem("configBtnList");
        if (findConfigLocalData) {
          findConfigLocalData = JSON.parse(findConfigLocalData);
        }
        if (
          (!findUnConfigLocalData && !findConfigLocalData) ||
          (findUnConfigLocalData &&
            findUnConfigLocalData.length == 0 &&
            findConfigLocalData &&
            findConfigLocalData.length == 0)
        ) {
          this.unConfigBtnList = [
            {
              id: 1,
              coordinate: null,
              zoneName: "正常的点",
              status: 0, //0是正常，1是报警
            },
            {
              id: 2,
              coordinate: null,
              zoneName: "报警的点",
              status: 1, //0是正常，1是报警
            },
          ];
        } else {
          this.configBtnList = findConfigLocalData;
          this.unConfigBtnList = findUnConfigLocalData;
          this.configBtnList.forEach((item) => {
            let singleData = {
              id: item.id,
              coordinate: item.coordinate,
              zoneName: item.zoneName,
              status: item.status,
            };
            let icon = L.icon({
              iconUrl: item.status == 1 ? this.alarmSrc : this.defaultIcon,
              iconSize: [30, 30],
            }); // 默认图标
            let marker = L.marker(JSON.parse(item.coordinate), {
              title: item.zoneName,
              icon: icon,
              id: item.id,
            });
            marker.id = item.id;
            this.map.addLayer(marker);
            marker.on("click", (ev) => {
              if (
                !this.map.pm.globalDragModeEnabled() &&
                !this.map.pm.globalRemovalEnabled()
              ) {
                let index = this.layerDatas.findIndex((x) => x.id == marker.id);
                this.popup = L.popup()
                  .setLatLng(JSON.parse(this.layerDatas[index].coordinate))
                  .setContent("<div>此处是" + item.zoneName + "</div>")
                  .openOn(this.map);
              }
              this.clickBtnItem(item);
            });

            marker.addEventListener("pm:edit", (e) => {
              // console.log(e)
              const layer = e.layer;
              let index = this.layerDatas.findIndex((x) => x.id == layer.id);
              if (index > -1) {
                this.layerDatas[index].coordinate = JSON.stringify(
                  layer._latlng
                );
              }
            });
            singleData.feature = marker;
            this.layerDatas.push(singleData);
          });
        }
      },
      dragStart($event, item) {
        event.dataTransfer.setData("drag_item", JSON.stringify(item));
        // console.log($event)
        $event.target.style.color = "red";
        this.mousePoint = "grabbing"
      },
      dragEnd($event, item) {
        $event.target.style.color = "";
        this.mousePoint = "grab"
      },
      receiveOnBtn(event, target) {
        let data = event.dataTransfer.getData("drag_item");
        if (data) {
          data = JSON.parse(data);
          this.currentSelectLeftBtnItem = data;
          // console.log(data);
          this.setMapIcon(event, data);
        }
      },
      setMapIcon(event, data) {
        this.map.pm.disableGlobalEditMode(); //不行只保留这一行
        let newPoint = L.point([event.layerX, event.layerY]);
        let newLatLng = this.map.containerPointToLatLng(newPoint);
        let icon = L.icon({
          iconUrl: data.status == 1 ? this.alarmIcon : this.defaultIcon,
          iconSize: [30, 30],
        }); // 默认图标
        let marker = L.marker(newLatLng, {
          title: data.zoneName,
          icon: icon,
          id: data.id,
        });
        marker.id = data.id;
        this.map.addLayer(marker);
        this.clickBtnItem(data);
        marker.on("click", (ev) => {
          if (
            !this.map.pm.globalDragModeEnabled() &&
            !this.map.pm.globalRemovalEnabled()
          ) {
            let index = this.layerDatas.findIndex((x) => x.id == marker.id);
            this.popup = L.popup()
              .setLatLng(JSON.parse(this.layerDatas[index].coordinate))
              .setContent("<div>此处是" + item.zoneName + "</div>")
              .openOn(this.map);
          }
          this.clickBtnItem(data);
        });
        marker.addEventListener("pm:edit", (e) => {
          // console.log(e, '++')
          const layer = e.layer;
          let index = this.layerDatas.findIndex((x) => x.id == layer.id);
          if (index > -1) {
            this.layerDatas[index].coordinate = JSON.stringify(layer._latlng);
          }
        });
        this.addLayer(marker);
      },
      clickBtnItem(item) {
        this.currentSelectLeftBtnItem = item;
        this.map.eachLayer((layer) => {
          if (layer.id) {
            if (layer.id == item.id) {
              layer._icon.style.border = "1px dashed #000";
            } else {
              layer._icon.style.border = "1px solid transparent";
            }
          }
        });
      },
      addLayer(data) {
        // 添加地图标记点逻辑
        if (data && data.hasOwnProperty("id")) {
          let item = {
            id: data.id,
            zoneName: data.options.title,
            coordinate: JSON.stringify(data._latlng),
            feature: data,
            status: data.status,
          };
          this.layerDatas.push(item);
          if (this.unConfigBtnList && this.unConfigBtnList.length) {
            let index = this.unConfigBtnList.findIndex((x) => x.id == data.id);
            let singleItem = this.unConfigBtnList.find((x) => x.id == data.id);
            singleItem.coordinate = JSON.stringify(data._latlng);
            this.unConfigBtnList.splice(index, 1);
            this.configBtnList.push(singleItem);
          }
        }
      },
      initMap() {
        // 地图初始化渲染
        this.map = L.map("lookMap", {
          crs: L.CRS.Simple,
          minZoom: -1,
          // zoom: this.zoom,
          maxZoom: 3,
          attributionControl: false,
          boxZoom: false,
          zoomSnap: 0.5,
          zoomDelta: 0.5,
          wheelPxPerZoomLevel: 200,
          // center: [607.5,556]
        });
        const imageWidth = 1215;
        const imageHeight = 1112;
        const bounds = [
          [0, 0],
          [imageHeight, imageWidth],
        ];
        const imageOverlay = L.imageOverlay("map/map.png", bounds, {
          interactive: true,
          pmIgnore: true,
        }).addTo(this.map);
        this.map.fitBounds(bounds);
        this.map.setMaxBounds(bounds);
        this.initDrawSetting();
        // 地图事件监听
        this.addMapListener();
        // this.map.setZoom(this.zoom)
      },
      initDrawSetting() {
        // 插件的一些初始化配置设定
        if (this.map && this.map.pm) {
          this.map.pm.addControls({
            // 工具栏
            position: "topleft", // 显示位置
            drawMarker: false, //禁用标点
            drawCircleMarker: false, // 圆形marker禁用
            drawPolyline: false, // 画线禁用
            drawRectangle: false, // 画矩形禁用
            drawCircle: false, // 画圆禁用
            cutPolygon: false, // 裁剪禁用
            rotateMode: false, // 旋转功能禁用
            editMode: false, //编辑多边形禁用
            drawPolygon: false, //绘制多边形禁用
            drawText: false, //禁用文本
          });
          this.map.pm.setLang("zh"); // 设置语言
        }
      },
      savePos() {
        try {
          localStorage.setItem(
            "unConfigBtnList",
            JSON.stringify(this.unConfigBtnList)
          );
          localStorage.setItem(
            "configBtnList",
            JSON.stringify(this.configBtnList)
          );
          this.$message.success("保存成功");
        } catch (e) {
          this.$message.success("保存失败");
        }
      },
      clearAllPos() {
        if (this.layerDatas && this.layerDatas.length) {
          this.layerDatas.forEach((item) => {
            item.feature.remove();
          });
          this.layerDatas = [];
          if (this.configBtnList) {
            this.configBtnList.forEach((item) => {
              this.unConfigBtnList.push(item);
            });
          }
          this.configBtnList = [];
          this.currentSelectLeftBtnItem = null;
          if (this.popup) {
            this.popup.close();
          }
        }
      },
      handleClickClearAllPos() {
        this.$confirm(
          "此操作将全部清空地图上的点位, 是否继续?",
          "提示(清空后仍需保存，才能清空)",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            this.clearAllPos();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      },
      refresh() {
        //还原成接口渲染的样子
        this.clearAllPos();
        this.getList();
      },
      addMapListener() {
        // 增加一些事件监听 以便做配置
        if (this.map) {
          this.map.addEventListener("pm:remove", this.removeEvent);
        }
      },
      removeMapListener() {
        // 移除事件监听
        if (this.map) {
          this.map.removeEventListener("pm:remove", this.removeEvent);
        }
      },
      removeLayer(id) {
        // 删除地图标记点逻辑
        if (this.layerDatas && this.layerDatas.length) {
          const layerIndex = this.layerDatas.findIndex((x) => x.id == id);
          const configBtnIndex = this.configBtnList.findIndex(
            (x) => x.id == id
          );
          const configBtnItem = this.configBtnList.find((x) => x.id == id);
          if (layerIndex > -1) {
            this.unConfigBtnList.push(configBtnItem);
            this.configBtnList.splice(configBtnIndex, 1);
            this.layerDatas.splice(layerIndex, 1);
          }
          if (
            this.currentSelectLeftBtnItem &&
            this.currentSelectLeftBtnItem.id == id
          ) {
            this.currentSelectLeftBtnItem = null;
          }
        }
      },
      removeEvent(e) {
        // 地图标记点删除事件
        if (e) {
          // console.log(e, "removeEvent");
          const layer = e.layer;
          const id = layer.id;
          this.removeLayer(id);
        }
      },
    },
  };
</script>

<style lang="less" scoped>
  .app-container {
    width: 100%;
    // height: 100%;
    height: calc(100vh - 60px);
    padding: 16px;
    display: flex;
    box-sizing: border-box;
    .left-container {
      width: 184px;
      height: 100%;
      margin-right: 16px;
      display: flex;
      flex-direction: column;
      .up-list {
        width: 100%;
        flex: 1;
        .leftList-container {
          width: 100%;
          height: 100%;
          // border: 1px solid #f5f5f5;
          overflow-x: hidden;
          overflow-y: auto;
          .unConfig-container {
            width: 100%;
            .unConfig-title {
              width: 100%;
              height: 30px;
              display: flex;
              align-items: center;
              .expand {
                margin-right: 8px;
                transform: rotateX(180deg);
                cursor: pointer;
              }
              .unExpand {
                margin-right: 8px;
                transform: rotateZ(90deg);
                cursor: pointer;
              }
            }
          }
          .config-container {
            width: 100%;
            .config-title {
              width: 100%;
              height: 30px;
              display: flex;
              align-items: center;
              .expand {
                margin-right: 8px;
                transform: rotateX(180deg);
                cursor: pointer;
              }
              .unExpand {
                margin-right: 8px;
                transform: rotateZ(90deg);
                cursor: pointer;
              }
            }
          }
          .config-list,
          .unConfig-list {
            width: 100%;
          }
          .list-item {
            width: 100%;
            height: auto;
            padding: 16px;
            border: 1px solid inherit;
            box-sizing: border-box;
            .item-content {
              width: 100%;
              height: 100%;
              display: flex;
              align-items: center;
              .svg-img-icon {
                margin-right: 8px;
                width: auto;
              }
            }
          }
          .list-item.active-item {
            border: 1px solid #a0cfff;
          }
          .list-item:hover {
            // border: 1px solid #a0cfff;
            background: #15314b;
            color: #a0cfff;
          }
        }
      }

      .down-btn {
        width: 100%;
        height: 40px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }

    #lookMap {
      // width: 100%;
      flex: 1;
      height: 100%;
      position: relative;
      .operaBtn-container {
        position: absolute;
        box-sizing: border-box;
        left: 10px;
        top: 85px;
        width: 34px;
        height: 64px;
        z-index: 801;
        #orderBack-step4 {
          width: 30px;
          height: 28px;
          display: flex;
          justify-content: center;
          align-items: center;
          border: 2px solid #ccc;
          border-bottom: 1px solid #ccc;
          i {
            font-size: 21px;
          }
        }
        #orderBack-step5 {
          width: 30px;
          height: 30px;
          display: flex;
          justify-content: center;
          align-items: center;
          border: 2px solid #ccc;
          border-top: 1px solid #ccc;
          i {
            font-size: 23px;
          }
        }
      }
      
    }
    ::v-deep {
      .leaflet-div-icon {
        background: transparent;
        border: 0;
      }
      .marker_icon {
        display: flex;
        img {
          max-width: 100% !important;
          max-height: 100% !important;
          display: block;
          margin: auto;
        }
      }
    }
    // .leaflet-container {
    //   background: #888f96;
    // }
  }
</style>
